package com.huan.springboot.config;

import com.huan.springboot.properties.MultiMongoProperties;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.net.UnknownHostException;

/**
 * 多个MongoDB的具体配置
 *
 * @author huan.fu
 * @date 2018/4/24 - 15:28
 */
@Configuration
public class MultiMongoConfig {

	@Autowired
	private MultiMongoProperties multiMongoProperties;

	@Bean(name = PersonsMongoConfig.MONGO_TEMPLATE_REF)
	@Primary
	public MongoTemplate personsMongoTemplateRef() {
		return new MongoTemplate(personsMongoDbFactory());
	}

	@Bean(name = StudyMongoConfig.MONGO_TEMPLATE_REF)
	public MongoTemplate studyMongoTemplateRef() throws UnknownHostException {
		return new MongoTemplate(studyMongoDbFactory());
	}

	@Bean
	@Primary
	public MongoDbFactory personsMongoDbFactory() {
		return new SimpleMongoDbFactory(new MongoClient(multiMongoProperties.getPersons().getHost(),
				multiMongoProperties.getPersons().getPort())
				, multiMongoProperties.getPersons().getDatabase());
	}

	@Bean
	public MongoDbFactory studyMongoDbFactory() throws UnknownHostException {
		return new SimpleMongoDbFactory(new MongoClientURI(multiMongoProperties.getStudy().getUri()));
	}
}
